<template>
    <div class="categories">
        <el-breadcrumb separator="/" class="breadcrumb">
            <el-breadcrumb-item>
                <a :href="urls.home" data-nuxt-link>Home</a>
            </el-breadcrumb-item>
            <el-breadcrumb-item>
                <a :href="urls.type" data-nuxt-link>{{ type }}</a>
            </el-breadcrumb-item>
            <el-breadcrumb-item>{{ name }}</el-breadcrumb-item>
        </el-breadcrumb>

        <div class="content">
            <div class="type-apps">
                <div class="title">{{ name }} apps</div>
                <div class="percent-total">
                    <div class="current">Top 1 ~ {{ displayedApps.length + ' / '}}</div>
                    <div class="total">Total {{ total }}</div>
                </div>
                <GoogleAdCollect
                    id="8365889802"
                    adm-id="div-gpt-ad-1747196180680-0"
                    name="APK_Categories_Display_3"
                    parent-page="Categories"
                    @adSuccess="handleAdSuccess"
                    @adError="handleAdError"
                />
                <div class="page-type-apps">
                    <a :href="getDetailUrl(app)" v-for="app in displayedApps" :key="app.id" class="app-item" @click="handleClickApp(type, app.name)">
                        <div class="app-icon">
                            <img :src="app.icon" :alt="app.name">
                        </div>
                        <div class="app-info">
                            <div class="app-name">{{ app.name }}</div>
                            <div class="app-rating">{{ app.rating }} <div class="rating">★</div></div>
                        </div>
                    </a>
                </div>
                <div v-if="hasMore" class="show-more-btn" @click="loadMore">
                    Show More {{ name }} apps
                </div>
                <div v-else class="the-end">
                    <el-icon><WarnTriangleFilled /></el-icon>
                    The End ~
                </div>
            </div>
            <TopDownloads adSlot='3879849887' admId='div-gpt-ad-1747196610971-0' name='APK_Categories_Display_4' parent-page="Categories" />
        </div>
    </div>
</template>

<script setup>
import GoogleAdCollect from '@/components/GoogleAdCollect.vue'
import TopDownloads from '@/components/TopDownloads.vue'
import { useFetch, useRoute } from '#app';
import { ref, computed, onMounted } from 'vue'
import { homeParams } from '~/utils/homeParams'

definePageMeta({
    title: 'category',
    layout: 'default'
})

const route = useRoute()    
const type = route.query.type
const name = decodeURIComponent(new URLSearchParams(route.fullPath.split('?')[1]).get('name')) || ''
const slug = route.params.category
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const apps = ref([])

// 存储所有生成的 URL
const urls = ref({
    home: '',
    type: ''
})

const generateUrls = () => {
    if (!process.client) return

    // 生成首页 URL
    urls.value.home = `/?${new URLSearchParams(homeParams()).toString()}`
    
    // 生成分类页 URL
    urls.value.type = `/${type}?${new URLSearchParams(homeParams()).toString()}`
}

// 在组件挂载后生成所有 URL
onMounted(() => {
    generateUrls()
})

const displayedApps = computed(() => {
    return apps.value.slice(0, currentPage.value * pageSize.value - 1)
})

const hasMore = computed(() => {
    return displayedApps.value.length < apps.value.length
})

async function loadMore() {
    pageSize.value += 9
}

try {
    const { data: categoryData } = await useFetch(`/api/category/${slug}`);
    if (categoryData.value) {
        apps.value = categoryData.value
        total.value = categoryData.value.length
    }
} catch (error) {
    console.error('Failed to load initial apps:', error)
}

const getDetailUrl = (item) => {
    const queryParams = {
        type: type,
        slug: item.slug,
        ...homeParams()
    }
    return `/details?${new URLSearchParams(queryParams).toString()}`
}

const handleClickApp = (type, name) => {
    logEvent('Click_APP', {
        Subzone: type,
        App: name,
    })
}

const handleAdSuccess = () => {
    console.log('广告加载成功')
}

const handleAdError = () => {
    console.log('广告加载失败')
}
</script>

<style scoped lang="scss">
.categories {
    .breadcrumb {
        @media screen and (max-width: 768px) {
            display: none;
        }
    }
    .content {
        display: grid;
        grid-template-columns: minmax(0, 2fr) minmax(0, 1fr);
        gap: 5rem;
        @media screen and (max-width: 768px) {
            grid-template-columns: 1fr;
            gap: 0;
            overflow: hidden;
            > * {
                min-width: 0;
                width: 100%;
            }
        }
        .type-apps {
            margin-top: 1rem;
            .title {
                @include title;
            }
            .percent-total {
                display: flex;
                justify-content: center;
                margin: 1rem 0;
                padding: 12px 0;
                background-color: #f5f5f5;
                width: 100%;;
                .current {
                    font-size: .8rem;
                }
                .total {
                    font-size: .8rem;
                    margin-left: .3rem;
                    color: #999;
                }
            }
            .page-type-apps {
                display: grid;
                grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
                gap: 1rem;
                margin: 1rem 0;
                
                .app-item {
                    display: flex;
                    align-items: center;
                    flex-direction: column;
                    
                    /* padding: 1rem; */
                    /* border: 1px solid #eee; */
                    border-radius: 0.5rem;
                    text-decoration: none;
                    color: #000;
                    gap: 1rem;
                    
                    .app-icon {
                        width: 4.5rem;
                        height: 4.5rem;
                        
                        img {
                            width: 100%;
                            height: 100%;
                            object-fit: cover;
                            border-radius: 0.5rem;
                        }
                    }
                    
                    .app-info {
                        /* flex: 1; */
                        display: flex;
                        flex-direction: column;
                        align-items: center;
                        .app-name {
                            font-weight: 500;
                            margin: 0.2rem 0;
                        }
                        
                        .app-rating {
                            color: #F78B17;
                            display: flex;
                            align-items: center;
                            gap: .2rem;
                            .rating {
                                color: #666;
                                font-size: .8rem;
                            }
                        }
                    }
                }
                @media screen and (max-width: 768px) {
                    grid-template-columns: repeat(auto-fill, minmax(100px, 1fr));
                    .app-item {
                        /* flex-direction: column; */
                        gap: 0;
                        .app-info {
                            display: flex;
                            flex-direction: column;
                            align-items: center;
                            width: 100%;
                            .app-name {
                                @include ellipsis;
                                width: 100%;
                                text-align: center;
                            }
                        }
                    }
                }
            }
            .show-more-btn {
                padding: .6rem 1.2rem;
                color: #fff;
                background-color: #F78B17;
                border-radius: 2rem;
                text-align: center;
                margin: 1rem;
                cursor: pointer;
                transition: background-color 0.3s;
                
                /* &:hover {
                    background-color: darken(#F78B17, 10%);
                } */
            }
            .the-end {
                color: #9a9a9a;
                font-size: 12px;
                margin: 1rem;
                display: flex;
                align-items: center;
                justify-content: center;
                .el-icon {
                    font-size: 1.2rem;
                    color: #cccccc
                }
            }
        }
    }
}
</style>